<template>
  <div class="app-container">
    <el-button type="success" @click="dialogVisible = true">添加用户</el-button>
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="修改用户信息" :visible.sync="dialogUpdateVisible" width="30%">
      <el-form ref="form" :model="updateForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="updateForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="updateForm.password"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <el-input v-model="updateForm.avatar"></el-input>
        </el-form-item>

        <el-form-item label>
          <el-avatar :size="60">
            <img :src="updateForm.avatar" />

            
          </el-avatar>
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/upload"
             
              multiple
              :show-file-list="true"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
        </el-form-item>

        <el-form-item label="角色">
          <!-- <el-input v-model="updateForm.role"></el-input>-->
          <el-select v-model="updateForm.role" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogUpdateVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleUpdateSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <el-table
      :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
      style="width: 100%"
    >
      <el-table-column label="注册时间" prop="createAt"></el-table-column>
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column label="用户名" prop="username"></el-table-column>
      <el-table-column label="头像">
        <template slot-scope="scope">
          <el-avatar :size="60">
            <img :src="scope.row.avatar" />
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="角色" prop="role"></el-table-column>
      <el-table-column label="是否禁用">
        <!-- prop="deleteAt" -->

        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.deleteAt == undefined">OK</el-tag>
          <el-tag type="danger" v-else>已删除</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="right">
        <template slot="header" slot-scope="scope">
          <el-input v-model="search" size="mini" placeholder="输入关键字搜索" />
        </template>
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">Edit</el-button>

          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            v-if="scope.row.deleteAt == undefined"
          >禁用</el-button>
          <el-button
            size="mini"
            type="success"
            @click="handleEnable(scope.$index, scope.row)"
            v-else
          >启用</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :page-count="totalPage"
      :current-page="currPage"
      @current-change="handleCurrentChange"
    ></el-pagination>
  </div>
</template>
<script>
import { getPageList,del,add,update,enable } from "@/api/userManager";
import { formatTime } from "@/utils/dateformat";
import { Message } from 'element-ui'

export default {
  data() {
    return {
      tableData: [
      ],
      search: "",
      currPage: 0,
      totalPage: 0,
      pageSize: 10,
      dialogVisible: false,
      form:{},
      updateForm:{},
      dialogUpdateVisible:false,
      options: [{
        value: 'ADMIN',
        label: '管理员'
      },{
        value: 'USER',
        label: '用户'
      }],
      fileList: [ 
      ]
    };
  },
  created() {
    this.loadPage(1, this.pageSize);
  },
  methods: {
    handleAvatarSuccess(res, file) {
      if (res.code != 20000) {
        Message({
          message: '上传失败' + res.message,
          type: 'fail',
          duration: 1 * 1000
        })
        return
      }
      const iurl = "http://localhost:8080/download/" + res.data;
      this.updateForm.avatar = iurl;
    },
    beforeAvatarUpload(file) {
      let isImg = file.type === 'image/jpeg';
      isImg = isImg || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImg) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isImg && isLt2M;
    },
    loadPage(page, size) {
  
    getPageList(page, size).then((resp) => {
        this.currPage = resp.data.currPage;
        this.totalPage = resp.data.totalPage;
        this.tableData = resp.data.data;

        this.tableData.forEach((element) => {
          element.createAt = formatTime(element.createAt / 1000);
        });

        console.log(JSON.stringify(resp));
      });
    },
    handleCurrentChange(currP) {
      console.log(`当前页: ${currP}`);
      this.loadPage(currP,this.pageSize)
    },
    handleEdit(index, row) {
      console.log(index, row);
      this.updateForm =  JSON.parse(JSON.stringify(row))
      this.dialogUpdateVisible = true
    },
    handleDelete(index, row) {
      console.log(index, row);
      del(row.id).then(resp => {
        Message({
          message: '删除成功',
          type: 'success',
          duration: 1 * 1000
        })
        this.loadPage(this.currPage,this.pageSize)
      })
    },
    handleEnable(index, row) {
      console.log(index, row);
      enable(row.id).then(resp => {
        Message({
          message: '启用成功',
          type: 'success',
          duration: 1 * 1000
        })
        this.loadPage(this.currPage,this.pageSize)
      })
    },
    handleSubmit() {
      console.log(JSON.stringify(this.form));
      add(this.form).then( resp => {
        this.dialogVisible = false
         Message({
          message: '添加成功',
          type: 'success',
          duration: 1 * 1000
        })
        this.loadPage(this.currPage,this.pageSize)
        this.form = {}
      })
    },
    handleUpdateSubmit(){
      console.log(JSON.stringify(this.updateForm));

      update(this.updateForm.id,this.updateForm).then(resp => {

        this.dialogUpdateVisible = false
         Message({
          message: '修改成功',
          type: 'success',
          duration: 1 * 1000
        })
        this.loadPage(this.currPage,this.pageSize)
      
      })
    }
  },
};
</script>